var createError = require('http-errors');
var express = require('express');
var router = express.Router();
var jwt = require('../lib/jsonwebtoken')

/* Generator Router. */

module.exports = {
    type: "prefix",
    prefix: "/api/v1",
    register: function(controller) {
        var prefix = controller.prefix === false? "" : this.prefix;
        controller.locations.forEach(location => {
            var routerPath = prefix+location.path;
            var reqMethod = location.method ? location.method: "get";
            router[reqMethod](routerPath, location.executor);
            router.all(routerPath, (req, res, next) => {
                next(createError(405))
            })
            location.router = router;
        })
        return controller
    },
    beforeRoute: function(req, res, next) {
        var token = req.signedCookies.Authorization
        jwt.verify(token, (err, decode) => {
            if(err) {
                next(createError(401))
            } else {
                model.User.findOne({where: {account: decode.account}}).then(user => {
                    if(null == user) {
                        res.clearCookie('Authorization')
                        next(createError(401))
                    } else {
                        req.user = user.dataValues;
                        next()
                    }
                })
            }
        })
    }
}
